package com.ugoodtech.mdcc.client.controller;

import com.ugoodtech.mdcc.client.dto.JsonResponse;
import com.ugoodtech.mdcc.client.dto.LabelValue;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.repository.DepartmentRepository;
import com.ugoodtech.mdcc.core.repository.NationRepository;
import com.ugoodtech.mdcc.core.repository.UserProfileRepository;
import com.ugoodtech.mdcc.core.repository.UserRepository;
import com.ugoodtech.mdcc.core.service.NationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.annotations.ApiIgnore;

import java.io.BufferedReader;
import java.io.FileReader;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Copyright © 2013 All Rights Reserved, Ugood Technology, Inc.
 */
@Api(description = "获取省市接口")
@Controller
@RequestMapping("/nation")
public class NationController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(NationController.class);

    @Autowired
    private NationService nationService;

    @Autowired
    private NationRepository nationRepository;

    @Autowired
    private DepartmentRepository departmentRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserProfileRepository userProfileRepository;


    @ApiOperation("获取当前用户负责的省份")
    @RequestMapping(value = "/getCreateProvinces", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getCreateProvinces(Principal principal) {
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此用户");
        }
        if (clientUser.getUserType().equals(UserType.dealers)) {
            return getProvinces(principal, false);
        }
        List<LabelValue> labelValues = new ArrayList<>();
        UserProfile userProfile = userProfileRepository.findByUserId(clientUser.getId());
        List<Nation> nationList = userProfile.getNationList();
        if (nationList == null || nationList.size() <= 0) {
            nationList = nationRepository.findProvince();
            labelValues = toLableValue(nationList);
            return JsonResponse.successResponseWithData(this.getLabelValueArrayForString(labelValues, false));
        }
        if (null != nationList) {
            labelValues = toLableValue(nationList);
        }
        return JsonResponse.successResponseWithData(this.getLabelValueArrayForString(labelValues, false));
    }

    @ApiOperation("获取当前用户负责的省份")
    @RequestMapping(value = "/getMyProvinces", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getMyProvinces(Principal principal) {
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此用户");
        }
//        if (clientUser.getUserType().equals(UserType.dealers)) {
        return getProvinces(principal, false);
//        }
//        List<LabelValue> labelValues = new ArrayList<>();
//        UserProfile userProfile = userProfileRepository.findByUserId(clientUser.getId());
//        List<Nation> nationList = userProfile.getNationList();
//        if (nationList == null || nationList.size() <= 0) {
//            nationList = (List<Nation>) nationRepository.findAll();
//            labelValues = toLableValue(nationList);
//            return JsonResponse.successResponseWithData(this.getLabelValueArrayForString(labelValues, false));
//        }
//        if (null != nationList) {
//            labelValues = toLableValue(nationList);
//        }
//        return JsonResponse.successResponseWithData(this.getLabelValueArrayForString(labelValues, false));
    }

    private List<LabelValue> toLableValue(List<Nation> nationList) {
        List<LabelValue> labelValues = new ArrayList<>();
        for (Nation nation : nationList) {
            if (nation.getProvince().equals("中华人民共和国")) {
                continue;
            }
            LabelValue labelValue = new LabelValue(nation.getProvince(), nation.getCode() + "");
            labelValues.add(labelValue);
        }
        return labelValues;
    }


    @ApiOperation("获取省")
    @RequestMapping(value = "/getProvinces", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getProvinces(Principal principal,
                                     @ApiIgnore boolean addAll
    ) {
        if (logger.isDebugEnabled()) {
            logger.debug("--------------getProvinces---------------");
        }
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此用户");
        }
        Iterable<Nation> nations = nationService.findAllProvinces();
        List<LabelValue> labelValues = new ArrayList<>();
        if (null != nations) {
            labelValues = toLableValue((List<Nation>) nations);
        }
        return JsonResponse.successResponseWithData(this.getLabelValueArrayForString(labelValues, addAll));
    }

    @ApiOperation("获取市")
    @RequestMapping(value = "/getCities", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getCities(
            @ApiParam("省的code") @RequestParam String code,
            @ApiIgnore @RequestParam(required = false) Boolean addAll
    ) throws Exception {
        if (logger.isDebugEnabled()) {
            logger.debug("--------------getCities---------------");
        }
        if (null == addAll) {
            addAll = false;
        }
        Iterable<Nation> nations = nationService.findCitiesInProvince(code);
        List<LabelValue> labelValues = new ArrayList<>();
        if (null != nations) {
            for (Nation nation : nations) {

                LabelValue labelValue = new LabelValue(nation.getCity(), nation.getCode() + "");
                labelValues.add(labelValue);

            }
        }
        return JsonResponse.successResponseWithData(this.getLabelValueArrayForString(labelValues, addAll));

    }

    @ApiOperation("获取区")
    @RequestMapping(value = "/getDistricts", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getDistricts(
            @ApiParam("市的code") @RequestParam String code,
            @RequestParam(required = false) Boolean addAll
    ) throws Exception {
        if (logger.isDebugEnabled()) {
            logger.debug("--------------getDistricts---------------");
        }
        if (null == addAll) {
            addAll = false;
        }

        Iterable<Nation> nations = nationService.findDistrictsInCity(code);
        List<LabelValue> labelValues = new ArrayList<>();
        if (null != nations) {
            for (Nation nation : nations) {
                LabelValue labelValue = new LabelValue(nation.getDistrict(), nation.getCode() + "");
                labelValues.add(labelValue);
            }
        }
        return JsonResponse.successResponseWithData(this.getLabelValueArrayForString(labelValues, addAll));

    }

    @ApiOperation("获取街道")
    @RequestMapping(value = "/getStreets", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getStreets(
            @ApiParam("区的code") @RequestParam String code,
            @RequestParam(required = false) Boolean addAll
    ) throws Exception {
        if (logger.isDebugEnabled()) {
            logger.debug("--------------getDistricts---------------");
        }
        if (null == addAll) {
            addAll = false;
        }

        Iterable<Nation> nations = nationService.findStreetsInDistrict(code);
        List<LabelValue> labelValues = new ArrayList<>();
        if (null != nations) {
            for (Nation nation : nations) {
                LabelValue labelValue = new LabelValue(nation.getStreet(), nation.getCode() + "");
                labelValues.add(labelValue);
            }
        }
        return JsonResponse.successResponseWithData(this.getLabelValueArrayForString(labelValues, addAll));

    }

    @ApiIgnore
    @ApiOperation("初始化数据")
    @RequestMapping(value = "/initNation", method = RequestMethod.GET)
    @ResponseBody
    public void initNation(

    ) throws Exception {
        System.out.println(new Date());
        BufferedReader br = new BufferedReader(new FileReader("E:\\data.json"));
        String line = "";
        StringBuffer buffer = new StringBuffer();
        while ((line = br.readLine()) != null) {
            buffer.append(line);
        }

        String jsonString = "";
        jsonString = buffer.toString();
        JSONArray dataArray1 = new JSONArray(jsonString);
        for (int i1 = 0; i1 < dataArray1.length(); i1++) {
            JSONObject jsonObject1 = dataArray1.getJSONObject(i1);
            Nation nation1 = new Nation();
            nation1.setProvince(jsonObject1.getString("name"));
            nation1.setCode(jsonObject1.getString("code"));
            nation1.setParent(null);
            nationRepository.save(nation1);
            JSONArray dataArray2 = new JSONArray(jsonObject1.getString("childs"));
            for (int i2 = 0; i2 < dataArray2.length(); i2++) {
                JSONObject jsonObject2 = dataArray2.getJSONObject(i2);
                Nation nation2 = new Nation();
                nation2.setCity(jsonObject2.getString("name"));
                nation2.setCode(jsonObject2.getString("code"));
                nation2.setParent(nation1);
                nationRepository.save(nation2);
                JSONArray dataArray3 = new JSONArray(jsonObject2.getString("childs"));
                for (int i3 = 0; i3 < dataArray3.length(); i3++) {
                    JSONObject jsonObject3 = dataArray3.getJSONObject(i3);
                    Nation nation3 = new Nation();
                    nation3.setDistrict(jsonObject3.getString("name"));
                    nation3.setCode(jsonObject3.getString("code"));
                    nation3.setParent(nation2);
                    nationRepository.save(nation3);
                    JSONArray dataArray4 = new JSONArray(jsonObject3.getString("childs"));
                    for (int i4 = 0; i4 < dataArray4.length(); i4++) {
                        JSONObject jsonObject4 = dataArray4.getJSONObject(i4);
                        Nation nation4 = new Nation();
                        nation4.setStreet(jsonObject4.getString("name"));
                        nation4.setCode(jsonObject4.getString("code"));
                        nation4.setParent(nation3);
                        nationRepository.save(nation4);
                    }
                }
            }
        }
        System.out.println(new Date());
    }

}
